package com.atfcm.queue;

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Set;

/**
 * @Author 96534
 * @create 2025/3/28 13:54
 */
public class T_347_前K个高频元素 {
    public static int[] topKFrequent(int[] nums, int k) {
        Map<Integer, Integer> numData = new HashMap<>();
        for (int num : nums) {
            numData.put(num, numData.getOrDefault(num,0)+1);
        }
        PriorityQueue<Integer> queue = new PriorityQueue<>(k, new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                Integer value = numData.get(o1);
                Integer value1 = numData.get(o2);

                return value == value1 ? 0 : (value > value1 ? 1 : -1);
            }
        });

        for (Map.Entry<Integer, Integer> integerIntegerEntry : numData.entrySet()) {
            int num = integerIntegerEntry.getKey();
            if(queue.size() < k){
                queue.offer(num);
            }else if(numData.get(queue.peek()) < numData.get(num)) {
                queue.poll();
                queue.offer(num);
            }
        }

        int[] ints = new int[queue.size()];
        int i = 0;
        while(!queue.isEmpty()){
            ints[i++] = queue.poll();
        }
        return ints;
    }

    public static void main(String[] args) {
        int[] ints = {1, 1, 1, 2, 2, 3};
        topKFrequent(ints, 2);
    }
}
